import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'

axios.defaults.timeout = process.env.VUE_APP_TIMEOUT;  //超时时间
axios.defaults.baseURL = '/api';  //请求地址

//请求拦截
axios.interceptors.request.use(config => {
    config.headers.token = store.getters.token
    return config
}, error => Promise.reject(error))

//相应拦截
axios.interceptors.response.use(response => {
    // const { data } = config.data
    // return data
    const type = response.headers['content-type'];
    if (type.startsWith('application/json')) {
        const { data } = response.data;
        return data;
    }
    return response.data
}, error => {
    const msg = error.toString();
    if (msg.includes('timeout')) {
        Message.error('请求超时')
        return Promise.reject(error)
    }
    if (msg.includes('Network Error')) {
        Message.error('网络错误，请检查网络')
        return Promise.reject(error)
    }
    const { status } = error.response;
    switch (status) {
        case 401:
            Message.error('登录过期请重新登陆')
            break;
        case 404:
            const { msg } = error.response.data
            Message.error(msg + '接口不存在')
            break;
        case 500:
            Message.error('服务器内部错误')
            break;
        default:
            break;
    }
    return Promise.reject(error)
})

export default axios;